import { useRef, useState } from "react";
import styled from "styled-components";
import { Badge, Button, Divider, message, Modal, Table, Typography } from "antd";
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import { ModalForm, ProFormItem, ProFormText, ProFormTextArea, ProFormTreeSelect } from "@ant-design/pro-components";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import Link from "@/components/Link";
import SearchForm from "@/components/searchForm";
import { dmServiceDelete, dmServiceOperationApp, dmServicePage, dmServicePublish } from "@/api/sharing/dmService";
import { dataCatalogTree } from "@/api/sharing/dataCatalog";
import TryoutModal from "./modules/TryoutModal";
const queryItems = [
  {
    name: 'serviceName',
    label: '服务名称',
    type: 'INPUT',
  },
];

const DmServiceIndex = () => {
  const [queryParam, setQueryParam] = useState({});
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const tryoutModalRef = useRef(null);

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 50,
      render(text, _, index) {
        return (page.pageNo - 1) * page.pageSize + index + 1;
      }
    },
    {
      title: '服务名称',
      dataIndex: 'serviceName',
      render: (text, record) => (<Link to={"/dmService/" + record.id}>{text}</Link>)
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (text) => (<Badge status={text == '0' ? 'default' : 'processing'} text={text == '0' ? '未发布' : '已发布'} />)
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '服务描述',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      key: 'action',
      align: 'left',
      width: '200px',
      render: (_, record) => (
        <>
          {record.status == '0' && <DmServicePublishBtn onFinish={handlePublish} initialValues={{ id: record.id, resourceSign: record.id, publishName: record.serviceName }} trigger={<Link>发布</Link>} />}
          {record.status == '1' && <Link onClick={() => handleWithdraw(record)}>下线</Link>}
          <Divider type="vertical" />
          <Link onClick={() => tryoutModalRef.current.show(record)}>测试</Link>
          {record.status == '0' && <>
            <Divider type="vertical" />
            <Link to={"/dmService/" + record.id + '/edit'}>修改</Link>
            <Divider type="vertical" />
            <Link disabled={record.status == '1'} onClick={() => { deleteConfirm(record) }}> <Typography.Text type="danger">删除</Typography.Text></Link>
          </>}
        </>
      ),
    },
  ];

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-dmServiceIndex-dmServicePage', page, queryParam],
    queryFn: () => {
      return dmServicePage({
        pageNo: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam,
      }).then((res) => {
        return res?.result || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const deleteConfirm = (row) => {
    const ids = [row.id] || selectedRowKeys
    Modal.confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return dmServiceDelete(ids)
          .then((res) => {
            if (res.code === 200) {
              onSelectChange([], [])
              refetch()
              message.success('删除成功')
            }
          })
      },
      onCancel() { },
    });
  };

  const handlePublish = (values) => {
    return dmServicePublish(values).then((res) => {
      if (res.code === 200) {
        message.success('发布成功')
        refetch()
        return true
      }
    })
  }

  const handleWithdraw = (values) => {
    Modal.confirm({
      title: '确认下线服务?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return dmServiceOperationApp({ id: values.id }).then((res) => {
          if (res.code === 200) {
            message.success('撤回成功')
            refetch()
            return true
          }
        })
      },
      onCancel() { },
    });
  }

  return (<StyleWrap className="dm-service-index searchTableWrapper">
    <div className="searchTableHeader">达梦</div>
    <SearchForm
      onSearch={(values) => {
        if (JSON.stringify(values) !== JSON.stringify(queryParam)) {
          setQueryParam({ ...values })
        } else {
          refetch()
        }
      }}
      items={queryItems}
      buttons={<>
        <Link to={"/dmService/add"}><Button icon={<PlusOutlined />} type="primary">新增</Button></Link>
        {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
      </>}
    />
    <Table
      rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
      columns={columns}
      rowKey={(record) => record.id}
      loading={isFetching}
      dataSource={tableData?.list}
      pagination={{
        current: page.pageNo,
        pageSize: page.pageSize,
        total: tableData?.total,
        onChange: (pageNo, pageSize) => {
          setPage({ pageNo, pageSize })
        }
      }}
    />

    <TryoutModal ref={tryoutModalRef} />
  </StyleWrap>);
}

// 服务发布
const DmServicePublishBtn = (props) => {
  return (
    <ModalForm
      width={'600px'}
      title="数据资源发布"
      modalProps={{ destroyOnClose: true }}
      grid={true}
      {...props}
    >
      <ProFormItem name="id" hidden />
      <ProFormText name="publishName" disabled label="数据资源名称" placeholder="请输入资源名称" rules={[{ required: true, message: '资源名称不能为空' }]} />
      <ProFormText name="resourceSign" disabled label="数据资源标识" placeholder="请输入资源标识" rules={[{ required: true, message: '资源标识不能为空' }]} />
      <ProFormTreeSelect name="catalogId" label="数据资源目录" placeholder="请选择资源目录"
        fieldProps={{
          fieldNames: {
            label: 'catalogName',
            value: 'id',
            children: 'childTreeList',
          }
        }}
        rules={[{ required: true, message: '资源目录不能为空' }]}
        request={() => {
          return dataCatalogTree().then((res) => {
            return res.result || []
          })
        }} />
      <ProFormTextArea name="remark" label="数据资源描述" placeholder="请输入资源描述" />
    </ModalForm>
  )
}

const StyleWrap = styled.div`
  &.dm-service-index{
    padding: 16px;
  }
`

export default DmServiceIndex;